package com.tio.tiowebscoketdemo.handler.bus;

import cn.hutool.json.JSONUtil;
import com.tio.tiowebscoketdemo.common.ShowcaseSessionContext;
import com.tio.tiowebscoketdemo.common.WsBusType;
import com.tio.tiowebscoketdemo.common.intf.AbsShowcaseBsHandler;
import com.tio.tiowebscoketdemo.common.packets.P2PReqBody;
import com.tio.tiowebscoketdemo.common.packets.P2PRespBody;
import com.tio.tiowebscoketdemo.config.CaseServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.json.Json;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

/**
 * @author tanyaowu
 * 2017年3月27日 下午9:51:28
 */
public class P2PReqHandler extends AbsShowcaseBsHandler<P2PReqBody> {
	private static Logger log = LoggerFactory.getLogger(P2PReqHandler.class);


	/**
	 *
	 * @author tanyaowu
	 */
	public P2PReqHandler() {
	}

	/**
	 * @return
	 * @author tanyaowu
	 */
	@Override
	public Class<P2PReqBody> bodyClass() {
		return P2PReqBody.class;
	}

	/**
	 * @param wsRequest
	 * @param bsBody
	 * @param channelContext
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@Override
	public Object handler(WsRequest wsRequest, P2PReqBody bsBody, ChannelContext channelContext) throws Exception {
		log.info("收到点对点请求消息:{}", Json.toJson(bsBody));

		ShowcaseSessionContext showcaseSessionContext = (ShowcaseSessionContext) channelContext.get();

		P2PRespBody p2pRespBody = new P2PRespBody();
		p2pRespBody.setFromUserid(showcaseSessionContext.getUserid());
		p2pRespBody.setText(bsBody.getText());
		p2pRespBody.setType(WsBusType.P2P_RESP);

		WsResponse wsResponse = WsResponse.fromText(JSONUtil.toJsonStr(p2pRespBody), CaseServerConfig.CHARSET);
		String userid = "";
		Tio.sendToUser(channelContext.tioConfig, userid, wsResponse);
		return null;
	}
}
